package models

import (
	message "chat/common"
	"encoding/json"
	"fmt"

	"github.com/gomodule/redigo/redis"
)

type UserDao struct {
	pool *redis.Pool
}

var (
	MyUserDao *UserDao
)

func NewUserDao(pool *redis.Pool) (userDao *UserDao) {
	userDao = &UserDao{
		pool: pool,
	}
	return
}
func (that *UserDao) GetUserById(conn redis.Conn, id int) (user *message.User, err error) {
	res, err := redis.String(conn.Do("HGet", "user", id))
	if err != nil {
		if err == redis.ErrNil {
			err = Err_USER_NOTEXISTS
		}
		return
	}
	user = &message.User{}
	err = json.Unmarshal([]byte(res), &user)
	if err != nil {
		fmt.Println("反序列化失败，err=", err)
		return
	}
	return
}

func (that *UserDao) Login(userId int, userPwd string) (user *message.User, err error) {
	conn := that.pool.Get()
	defer conn.Close()
	user, err = that.GetUserById(conn, userId)
	if err != nil {
		fmt.Println(err)
		return
	}
	if user.UserPwd != userPwd {
		err = Err_USER_PWD
		return
	}
	return
}

func (that *UserDao) Register(user *message.User) (err error) {
	conn := that.pool.Get()
	defer conn.Close()
	_, err = that.GetUserById(conn, user.UserId)
	if err == nil {
		err = Err_USER_EXISTS
		return
	}
	fmt.Println(user)
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("注册入库反序列化失败，err=", err)
		return
	}
	_, err = conn.Do("Hset", "user", user.UserId, string(data))
	if err != nil {
		fmt.Println("注册入库错误，err=", err)
		return
	}
	return
}
